package com.yangluyao.test.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @author YLY
 * @ClassName CallableDemo
 * @Date 2020/5/22
 * @Version 1.0.2
 */
class MyThread implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "**************** come Callable ");
        TimeUnit.SECONDS.sleep(3);
        return 1024;
    }
}

/**
 * Callable线程是异步重启线程，如果要开启多个Callable线程，需要创建多个FutureTask
 * @author 81509
 */
public class CallableDemo {
    public static void main(String[] args) throws Exception {
        //FutureTask(Callable<V> callable)
        FutureTask<Integer> futureTask = new FutureTask<>(new MyThread());
        FutureTask<Integer> futureTask2 = new FutureTask<>(new MyThread());
        new Thread(futureTask, "AA").start();
        new Thread(futureTask2, "BB").start();
        System.out.println(Thread.currentThread().getName() + "**************** come main ");
        int result = 100;
        //futureTask.isDone()表示该线程是否执行完毕
        while (!futureTask.isDone()){

        }
        //futureTask.get() 获得Callable线程的计算结果，
        // 如果没有计算完成就要强行获取Callable值，会导致堵塞，直到计算完成
        System.out.println("************************ result: " + (result+futureTask.get()));
    }
}
